from sqlalchemy.orm import Session

from apis_module.dao.group_dao import GroupDao
from apis_module.jsonvo.group_vo import GroupTreeModel


class GroupService:
    @classmethod
    def get_groups_service(cls, result_db: Session):
        # group_tree_options = []
        result_groups = GroupDao().get_group_list(result_db)

        menu_tree_result = cls.get_group_tree(0, GroupTreeModel(group_tree=result_groups))
        # group_tree_options.append(dict(title='主类目', value='0', key='0', children=menu_tree_result))

        return menu_tree_result

    @classmethod
    def get_group_selector_service(cls, result_db: Session):
        """
        获得分类选择器数据集
        :param result_db: orm连接
        :return: 分类选择器数据集
        """
        result_groups = GroupDao().get_group_list(result_db)
        return cls.gen_group_selector(GroupTreeModel(group_tree=result_groups))

    @classmethod
    def get_group_tree(cls, pid: int, group_tree_model: GroupTreeModel):
        """
        嵌套递归方法：根据分类信息生成树形嵌套数据
        :param pid: 父类别ID
        :param group_tree_model: 分类列表信息
        :return: 分类树型嵌套
        """
        group_tree = []
        for group in group_tree_model.group_tree:
            if group.parent_code == pid:
                children = cls.get_group_tree(group.group_code, group_tree_model)
                group_list_data = {}
                if children:
                    group_list_data['groupId'] = group.group_code
                    group_list_data['name'] = group.group_name
                    group_list_data['thumbnail'] = group.group_thumbnail
                    group_list_data['children'] = children
                else:
                    group_list_data['groupId'] = group.group_code
                    group_list_data['name'] = group.group_name
                    group_list_data['thumbnail'] = group.group_thumbnail
                group_tree.append(group_list_data)

        return group_tree

    @classmethod
    def gen_group_selector(cls, group_tree_model: GroupTreeModel):
        """
        生成分类选择器数据集
        :param group_tree_model: 分类列表信息
        :return: 分类选择器数据集
        """
        aspects = []
        areas = []
        entitys = []
        for group in group_tree_model.group_tree:
            eazyGroup = {}
            eazyGroup['label'] = group.group_name
            eazyGroup['value'] = group.group_code

            match group.group_level:
                case 1:
                    aspects.append(eazyGroup)
                case 2:
                    areas.append(eazyGroup)
                case 3:
                    entitys.append(eazyGroup)

        sort_aspects = sorted(aspects, key=lambda k: k['value'])
        sort_areas = sorted(areas, key=lambda k: k['value'])
        sort_entitys = sorted(entitys, key=lambda k: k['value'])
        result = {
            'aspects': sort_aspects,
            'areas': sort_areas,
            'entitys': sort_entitys
        }
        return result
